import os
from datetime import datetime
from io import BytesIO
from utils import JsonResponse
import pandas as pd
from exts import db
from flask import Blueprint, render_template, request, flash, url_for, jsonify, Response, send_file, send_from_directory
from models import EmployeeModel, SubmissionModel
from werkzeug.utils import secure_filename, redirect

from services import employee_service

bp = Blueprint("employees", __name__, url_prefix="/employees")


@bp.route("/employees_list", methods=["GET"])
def employees_list():
    status, info = employee_service.show_all()
    if status:
        return JsonResponse.success(info.msg, info.data)
    else:
        return JsonResponse.error(info.msg, info.data)


@bp.route("/index", methods=["GET"])
def employee_page():
    return send_from_directory("static/paper", "index.html")


@bp.route("/query", methods=["POST", "GET"])
def query():
    data = request.get_json()
    em_name = data['em_name']
    email = data['email']
    identity = data['role']
    return employee_service.query(name=em_name, email=email, role=identity)


@bp.route("/add", methods=["POST"])
def add():
    data = request.get_json()
    if not data['em_name'].strip() or not data['email'].strip() or not data['role']:
        return JsonResponse.error("添加员工失败，信息不全。")
    # 必要字段检查
    # if not data or not all(key in data for key in ("em_name", "email", "role")):
    #     return JsonResponse.error("Missing data")
    # return jsonify({"error": "Missing data"}), 400

    em_name = data['em_name']
    email = data['email']
    identity = data['role']
    status, info = employee_service.add(em_name, email, identity)
    if status:
        return JsonResponse.success(info.msg, info.data)
    else:
        return JsonResponse.error(info.msg, info.data)
    # return employee_service.add(em_name, email, identity)


@bp.route("/uploadExcel", methods=["POST"])
def uploadExcel():
    if 'file' not in request.files:
        return JsonResponse.error("没有文件被上传")
        # return jsonify({"error": "没有文件被上传"}), 400
    file = request.files['file']
    status, info = employee_service.uploadExcel(file)
    if status:
        return JsonResponse.success(info.msg, info.data)
    else:
        return JsonResponse.error(info.msg, info.data)
    # return employee_service.uploadExcel(file)


@bp.route("/edit/<int:employee_id>", methods=["POST"])
def edit(employee_id):
    # 获取请求数据
    data = request.get_json()  # 假设您通过 JSON 发送数据
    if not data:
        return JsonResponse.error("没有接收到数据")
        # return jsonify({"error": "没有接收到数据"}), 400

    # 从请求数据中获取更新的信息
    name = data.get("em_name")
    email = data.get("email")
    role = data.get("role")

    # return employee_service.edit(employee_id=employee_id, name=name, email=email, role_description=role)
    status, info = employee_service.edit(employee_id=employee_id, name=name, email=email, role_description=role)
    if status:
        return JsonResponse.success(info.msg, info.data)
    else:
        return JsonResponse.error(info.msg, info.data)


@bp.route("/delete/<int:employee_id>", methods=["POST", "GET"])
def delete(employee_id):
    status, info = employee_service.delete(employee_id)
    if status:
        return JsonResponse.success(info.msg, info.data)
    else:
        return JsonResponse.error(info.msg, info.data)
    # return employee_service.delete(employee_id)


@bp.route("/bulk_delete", methods=["DELETE"])
def bulk_delete():
    # 从请求中获取要删除的员工 ID 列表
    data = request.get_json()
    if not data or 'ids' not in data:
        return JsonResponse.error("删除失败")
        # return jsonify({"error": "请求体中必须包含 'ids' 列表"}), 400

    ids_to_delete = data['ids']

    if not isinstance(ids_to_delete, list) or not all(isinstance(i, int) for i in ids_to_delete):
        return JsonResponse.error("删除失败")
    # return employee_service.bulk_delete(ids_to_delete)
    status, info = employee_service.bulk_delete(ids_to_delete)
    if status:
        return JsonResponse.success(info.msg, info.data)
    else:
        return JsonResponse.error(info.msg, info.data)


@bp.route("/batch_export", methods=["POST"])
def batch_export():
    return employee_service.batch_export()


@bp.route("/edit/leave/<int:employee_id>", methods=["POST"])
def leave_vacation(employee_id):
    data = request.get_json()
    if not data:
        return JsonResponse.error("没有接收到数据")
    # 从请求数据中获取更新的信息
    status = data.get("status")
    submisson = SubmissionModel.query.filter_by(description=status).first()
    status = submisson.status
    reason = data.get("reason")
    start_date = data.get("start_date")
    end_date = data.get("end_date")
    try:
        # 解析 ISO 8601 格式的日期
        start_date_dt = datetime.fromisoformat(start_date.replace("Z", "+00:00"))  # 将 'Z' 替换为 '+00:00' 以进行解析
        end_date_dt = datetime.fromisoformat(end_date.replace("Z", "+00:00"))
        start_date_local = start_date_dt.astimezone()
        end_date_local = end_date_dt.astimezone()
        # 将日期格式化为 'YYYY-MM-DD'
        start_date_formatted = start_date_local.strftime('%Y-%m-%d')
        end_date_formatted = end_date_local.strftime('%Y-%m-%d')
    except ValueError:
        return JsonResponse.error(message="日期格式无效")
        # return jsonify({"status": "error", "msg": "日期格式无效"}), 400

    status, info = employee_service.leave_vacation(employee_id=employee_id, status=status, reason=reason, start_date=start_date_formatted, end_date=end_date_formatted)
    if status:
        return JsonResponse.success(info.msg, info.data)
    else:
        return JsonResponse.error(info.msg, info.data)

@bp.route("/bulk_leave", methods=["POST"])
def bulk_leave():
    data = request.get_json()
    if not data:
        return JsonResponse.error("没有接收到数据")
    # 从请求数据中获取更新的信息
    ids_to_leave = data.get("ids")
    status = data.get("status")
    submisson = SubmissionModel.query.filter_by(description=status).first()
    status = submisson.status
    reason = data.get("reason")
    start_date = data.get("start_date")
    end_date = data.get("end_date")
    try:
        # 解析 ISO 8601 格式的日期
        start_date_dt = datetime.fromisoformat(start_date.replace("Z", "+00:00"))  # 将 'Z' 替换为 '+00:00' 以进行解析
        end_date_dt = datetime.fromisoformat(end_date.replace("Z", "+00:00"))
        start_date_local = start_date_dt.astimezone()
        end_date_local = end_date_dt.astimezone()
        # 将日期格式化为 'YYYY-MM-DD'
        start_date_formatted = start_date_local.strftime('%Y-%m-%d')
        end_date_formatted = end_date_local.strftime('%Y-%m-%d')
    except ValueError:
        return JsonResponse.error(message="日期格式无效")
        # return jsonify({"status": "error", "msg": "日期格式无效"}), 400

    status, info = employee_service.bulk_leave(employees_id=ids_to_leave, status=status, reason=reason,
                                                   start_date=start_date_formatted, end_date=end_date_formatted)
    if status:
        return JsonResponse.success(info.msg, info.data)
    else:
        return JsonResponse.error(info.msg, info.data)
